<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属SPU ID" prop="spuId">
        <el-input
          v-model="queryParams.spuId"
          placeholder="请输入所属SPU ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="SKU编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入SKU编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['product:sku:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:sku:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:sku:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['product:sku:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="skuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SKU ID" align="center" prop="id" />
      <el-table-column label="所属SPU ID" align="center" prop="spuId" />
      <el-table-column label="SKU编码" align="center" prop="code" />
      <el-table-column label="商品分类ID" align="center" prop="categoryId" />
      <el-table-column label="规格属性JSON" align="center" prop="specData" />
      <el-table-column label="销售价" align="center" prop="price" />
      <el-table-column label="原价" align="center" prop="originalPrice" />
      <el-table-column label="成本价" align="center" prop="costPrice" />
      <el-table-column label="库存数量" align="center" prop="stock" />
      <el-table-column label="库存预警值" align="center" prop="lowStock" />
      <el-table-column label="重量(g) 用于物流" align="center" prop="weight" />
      <el-table-column label="体积(cm³) 用于物流" align="center" prop="volume" />
      <el-table-column label="商品图片" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.productImages && scope.row.productImages.length > 0">
            <!-- 只显示第一张图片，通过索引0获取 -->
            <div style="display: inline-block; margin: 0 5px; vertical-align: middle">
              <image-preview :src="scope.row.productImages[0].url" :width="50" :height="50"/>
            </div>
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="状态：0-禁用，1-启用" align="center" prop="status" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['product:sku:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['product:sku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品SKU对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="skuRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="所属SPU ID" prop="spuId">
          <el-input v-model="form.spuId" placeholder="请输入所属SPU ID" />
        </el-form-item> -->
        <!--spu选择-->
        <el-form-item label="spu" prop="spuId">
          <el-select 
            v-model="form.spuId" 
            placeholder="请选择或输入SPU名称搜索" 
            clearable
            filterable 
            @input="handleSpuSearch"  
          >
            <el-option
              v-for="spu in productSpuList"
              :key="spu.id" 
              :label="spu.name"
              :value="spu.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="SKU编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入SKU编码" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-tree-select
            v-model="form.categoryId"
            :data="productCategoryOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择商品分类"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="销售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入销售价" />
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input v-model="form.originalPrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本价" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="库存预警值" prop="lowStock">
          <el-input v-model="form.lowStock" placeholder="请输入库存预警值" />
        </el-form-item>
        <el-form-item label="重量(g) 用于物流" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量(g) 用于物流" />
        </el-form-item>
        <el-form-item label="体积(cm³) 用于物流" prop="volume">
          <el-input v-model="form.volume" placeholder="请输入体积(cm³) 用于物流" />
        </el-form-item>
        <el-form-item label="商品图片" prop="productImages">
          <image-upload 
            v-model="form.productImages" 
            :limit="20"  
            multiple    
            @change="handleImageChange"  
          />
          <div class="text-xs text-gray-500 mt-1">
            支持上传多张图片，最多5张，按上传顺序排序
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sku">
import { listSku, getSku, delSku, addSku, updateSku } from "@/api/product/sku";
import { listProductCategory} from "@/api/product/productCategory";
import { listProductSpu } from "@/api/product/productSpu";
const { proxy } = getCurrentInstance();

const skuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const productCategoryOptions = ref([]);
const productSpuList = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    spuId: null,
    code: null,
    categoryId: null,
    status: null,
    createdAt: null,
  },
  rules: {
    spuId: [
      { required: true, message: "所属SPU ID不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "SKU编码不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "销售价不能为空", trigger: "blur" }
    ],
    stock: [
      { required: true, message: "库存数量不能为空", trigger: "blur" }
    ],
    productImages: [
      { 
        required: true, 
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error("请至少上传一张商品图片"));
          } else {
            callback();
          }
        },
        trigger: "change"
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品SKU列表 */
function getList() {
  loading.value = true;
  listSku(queryParams.value).then(response => {
    skuList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    spuId: null,
    code: null,
    categoryId: null,
    specData: null,
    price: null,
    originalPrice: null,
    costPrice: null,
    stock: null,
    lowStock: null,
    weight: null,
    volume: null,
    productImages: [],
    status: null
  };
  proxy.resetForm("skuRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getSpuList();
  getCategoryTreeselect();
  open.value = true;
  title.value = "添加商品SKU";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getSpuList();
  getCategoryTreeselect();
  const _id = row.id || ids.value
  getSku(_id).then(response => {
     const skuData = response.data;
     form.value = {
      ...skuData,
      // 确保productImages是数组（兼容后端可能返回null的情况）
      productImages: skuData.productImages || []
    };
    open.value = true;
    title.value = "修改商品SKU";
  });
}

/** 处理图片上传后的回调：设置排序值 */
function handleImageChange(images) {
console.log("handleImageChange",images)
  // 上传后按顺序设置sort（1,2,3...），并关联当前SKU/SPU
  form.value.productImages = images.map((img, index) => ({
    url: img.url, // 图片URL
    sort: index + 1, // 排序权重（按上传顺序）
    skuId: form.value.id || null, // 关联当前SKU
    spuId: form.value.spuId || null // 关联当前SPU
  }));
}

/** 查询商品分类下拉树结构 */
function getCategoryTreeselect() {
  listProductCategory().then(response => {
    productCategoryOptions.value = [];
    const data = { id: 0, name: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    productCategoryOptions.value.push(data);
  });
}
let querySpuParams=ref({pageSize:9999,name:''})
/** 查询商品SPU列表 */
function getSpuList() {
  loading.value = true;
  
  listProductSpu(querySpuParams.value).then(response => {
    productSpuList.value = response.rows;
  });
}
// 防抖函数：避免输入过程中频繁请求接口
function debounce(fn, delay = 300) {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

// 使用防抖处理搜索函数
const handleSpuSearch = debounce((inputValue) => {
  querySpuParams.value.name = inputValue.data || '';
  console.log("querySpuParams",querySpuParams)
  getSpuList();
});

/** 提交按钮 */
function submitForm() {
  proxy.$refs["skuRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        console.log("form.value",form.value)
        updateSku(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSku(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商品SKU编号为"' + _ids + '"的数据项？').then(function() {
    return delSku(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('product/sku/export', {
    ...queryParams.value
  }, `sku_${new Date().getTime()}.xlsx`)
}

getList();
</script>
